package com.hjc;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public class DOM4JTest {
    /**
     * xml文件路径
     */
    private static final String XML_PATH = "G:\\work-space\\my-project\\dw-test\\src\\main\\java\\com\\dw\\study\\dom\\books.xml";
    
    public static void main(String[] args) {
        // 创建SAXReader的对象reader
        SAXReader reader = new SAXReader();
        try (InputStream resource =
                     ClassLoader.getSystemClassLoader().getResourceAsStream("books.xml")) {
            // 通过reader对象的read方法加载books.xml文件, 获取Document对象。
            Document document = reader.read(resource);
            // 通过document对象获取根节点bookstore
            Element bookStore = document.getRootElement();
            // 遍历迭代器，获取根节点中的信息（书籍）
            for (Iterator<Element> it = bookStore.elementIterator(); it.hasNext(); ) {
                System.out.println("=====开始遍历某一本书=====");
                Element book = it.next();
                // 获取book的属性名以及 属性值
                List<Attribute> bookAttrs = book.attributes();
                for (Attribute attr : bookAttrs) {
                    System.out.println("属性名：" + attr.getName() + "--属性值：" + attr.getValue());
                }
                for (Iterator<Element> itt = book.elementIterator(); itt.hasNext(); ) {
                    Element bookChild = itt.next();
                    System.out.println("节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
                }
                System.out.println("=====结束遍历某一本书=====");
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}